package com.lagou.edu.utils;

import com.lagou.edu.listener.BeanDefinition;

import java.util.Map;

/**
 * @author wuyancheng
 */
public class GetBeanByType {
    /**
     * 判断按照类型查找到的对象数量
     * 超过1个对象，报错
     * @param objectMap
     * @param type
     * @return
     * @throws ClassNotFoundException
     */
    public static Object doGetBeanByType(Map<String, Object> objectMap, String type) throws Exception {
        Class<?> aClass = Class.forName(type);
        Object object = null;
        int count = 0;
        for(Map.Entry<String, Object> entry : objectMap.entrySet()){
            if (entry.getValue().getClass().isAssignableFrom(aClass)) {
                object = entry.getValue();
                count ++;
                if(count > 1){
                    throw new Exception("符合类型的对象过多，无法确定装配的对象");
                }
            }
        }
        return object;
    }

    /**
     * 根据类名获取对象，如果是子类的话也可以返回
     * 在Spring中会对同一个类的定义进行合并
     * @param beanDefinitionMap
     * @param className
     * @return
     */
    public static BeanDefinition doGetBeanDefinition(Map<String, BeanDefinition> beanDefinitionMap, String className) throws ClassNotFoundException {
        BeanDefinition beanDefinition = beanDefinitionMap.get(className);
        if(beanDefinition != null){
            return beanDefinition;
        }
        Class<?> aClass = Class.forName(className);
        for(Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()){
            Class<?> keyClass = Class.forName(entry.getKey());
            if(aClass.isAssignableFrom(keyClass)){
                return entry.getValue();
            }
        }
        return null;
    }
}
